use std::net::TcpStream;
mod controller;
mod utils;
use tauri::async_runtime::block_on;

// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[tauri::command]
fn check_frp_service_running(host: &str, port: u16) -> bool {
    TcpStream::connect((host, port)).is_ok()
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    println!("{}", std::env::consts::OS);
    println!("{}", std::env::consts::ARCH);
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![
            greet, 
            check_frp_service_running,
            crate::controller::frpcproxy::add_proxie,
            crate::controller::frpcproxy::del_proxie,
            crate::controller::frpcproxy::save_status,
            crate::controller::frpcproxy::save_proxie,
            crate::controller::frpcproxy::restart_server,
            crate::controller::setting::get_setting,
            crate::controller::setting::set_setting,
            crate::controller::frpcapi::frpc_run,
            crate::controller::frpcapi::frpc_stop,
            crate::controller::frpcapi::frpc_reload,
            crate::controller::frpcapi::frpc_check,
            crate::controller::frpcapi::download_and_extract_frpc,
        ])
        .on_window_event(|window, event| {
            use tauri::WindowEvent;
            if let WindowEvent::CloseRequested { .. } = event {
                println!("窗口关闭，调用 frpc_stop");
                let result = block_on(crate::controller::frpcapi::frpc_stop());
                // 不阻止关闭，避免死循环
                 println!("不阻止关闭，避免死循环");
            }
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
